//
//  QYBookDetailViewController.m
//  QingYue
//
//  Created by 崔明燃 on 2017/3/29.
//  Copyright © 2017年 com.lanou.product_A. All rights reserved.
//

#import "QYBookDetailViewController.h"

#import "QYBookDetailListHeaderView.h"
#import "QYBookDetailCommentTableViewCell.h"
#import "QYBookDetailModel.h"
#import "QYMoreCommentsModel.h"
#import "QYBookAddInfoVC.h"

static NSString *listTableViewCommentCell = @"listTableViewCommentCell";
static CGFloat listHeaderHeigh = 260;

@interface QYBookDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *listTableView;
@property (strong, nonatomic) QYBookDetailListHeaderView *listHeader; // 頭视图

@property (nonatomic, strong) QYBookDetailModel *bookModel;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UIButton *commitBtn;



@end

@implementation QYBookDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"图书详情";
    
    _commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _commitBtn.backgroundColor = MyGreenColor;
    [_commitBtn setTitle:@"借阅" forState:UIControlStateNormal];
    [_commitBtn addTarget:self action:@selector(commitBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_commitBtn];
    [_commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [self.view addSubview:self.listTableView];
    [_listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.bottom.equalTo(self.commitBtn.mas_top);
    }];


    
}

- (void)commitBtnAction {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定要借阅此书?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *act = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSDictionary *param = @{@"id" : _isbn,@"username":[kUserDefaults objectForKey:@"username"]};
        [[YCRequestDataService sharedManager] Post:@"Borrow" parameters:param success:^(id response) {
            if ([response[@"Code"] isEqualToString:@"成功"]) {
                kShowNet(@"借阅成功");
            } else {
                kTimeAfter(1, ^{kShowNet(response[@"Exception"]);});
            }
        } failure:^{
            kTimeAfter(1, ^{kShowNet(@"网络或服务器错误");});
        }];
    }];
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];

    [alert addAction:act];
    [alert addAction:act1];
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)loadData {
    NSDictionary *param = @{@"UserName":[kUserDefaults objectForKey:@"username"],
                            @"id":_isbn};
    
    [[YCRequestDataService sharedManager] Post:@"GetBook" parameters:param success:^(id response) {
        _bookModel = [[QYBookDetailModel alloc] initWithDataDic:response];
        
        NSDictionary *param = @{@"isbn":_isbn,
                                @"UserName":[kUserDefaults objectForKey:@"username"]};
        
        [[YCRequestDataService sharedManager] Post:@"GetCommentByIsbn" parameters:param success:^(id response) {
            
            _dataArr = [NSMutableArray new];
            
            NSArray *commentList = response[@"commentList"];
            [commentList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                QYMoreCommentsModel *model = [[QYMoreCommentsModel alloc] initWithDataDic:obj];
                [_dataArr addObject:model];
            }];
            
            [self.listTableView reloadData];
            
        } failure:^{
            
        }];
    } failure:^{
        
    }];
}


- (void)setIsbn:(NSString *)isbn {
    _isbn = isbn;
    
    [self loadData];
}

- (void)focusRequestWithParam:(NSDictionary *)param withAPI:(NSString *)api {
    
    [[YCRequestDataService sharedManager] Post:api parameters:param success:^(id response) {
        [self loadData];
    } failure:^{
        
    }];
}

- (void)thumpUpRequestWithParam:(NSDictionary *)param {
    [[YCRequestDataService sharedManager] Post:@"FabulousByID" parameters:param success:^(id response) {
        if ([response[@"Code"] isEqualToString:@"失败"]) {
            
        } else {
            [self loadData];
        }
    } failure:^{
        
    }];
}


#pragma mark - tableView delegate and datasoure
// 分几个section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return listHeaderHeigh;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

// 每个section里面cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (self.listHeader) {
        self.listHeader.model = _bookModel;
        __weak typeof(self) weakSelf = self;
        _listHeader.Lblock = ^(NSString *isbn, NSString *api) {
            NSDictionary *param = @{@"username":[kUserDefaults objectForKey:@"username"],
                                    @"isbn":isbn};
            [weakSelf focusRequestWithParam:param withAPI:api];
        };
    };
    
    return self.listHeader;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    QYBookDetailCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:listTableViewCommentCell forIndexPath:indexPath];
    
    __weak typeof(self) weakSelf = self;
    
    cell.thumbUpBlock = ^(NSNumber *c_id) {
        
        NSDictionary *param = @{@"id":c_id,
                                @"username":[kUserDefaults objectForKey:@"username"]};
        [weakSelf thumpUpRequestWithParam:param];
    };
    
    QYMoreCommentsModel *model = _dataArr[indexPath.row];
    cell.model = model;
    
    return cell;
}




#pragma mark - lazy load
- (UITableView *)listTableView {
    if (!_listTableView) {
        _listTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _listTableView.delegate = self;
        _listTableView.dataSource = self;
        _listTableView.estimatedRowHeight = 100;
        _listTableView.height = UITableViewAutomaticDimension;
        _listTableView.backgroundColor = [UIColor whiteColor];
        _listTableView.estimatedSectionFooterHeight = 0.0f;
        _listTableView.estimatedSectionHeaderHeight = 0.0f;
        _listTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        
        if (@available(iOS 11.0, *)) {
            _listTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }

        [_listTableView registerNib:[UINib nibWithNibName:@"QYBookDetailTableViewCell" bundle:nil] forCellReuseIdentifier:listTableViewCommentCell];
    }
    
    return _listTableView;
}

- (QYBookDetailListHeaderView *)listHeader {
    if (!_listHeader) {
        _listHeader = [[QYBookDetailListHeaderView alloc] initWithFrame:(CGRect){0, 0, self.view.width, listHeaderHeigh}];
        [_listHeader.addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _listHeader;
}

#pragma mark - Actions
- (void)addBtnAction {
    QYBookAddInfoVC *infoVC = [[QYBookAddInfoVC alloc] init];
    infoVC.model = _bookModel;
    [self.navigationController pushViewController:infoVC animated:YES];
}



@end
